package mybatis.generator;

import mybatis.generator.annotation.GeneratedSql;
import mybatis.generator.ext.GeneratorInterceptor;
import mybatis.generator.ext.InterceptorContext;
import mybatis.generator.support.Reflection;
import mybatis.generator.support.ResultInterceptor;
import mybatis.generator.support.parse.EntityMeta;
import mybatis.generator.support.generator.EntityNestQueryGenerator;
import mybatis.generator.support.parse.MapperStatementParser;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by huangdachao on 2018/6/17 01:06.
 */
@org.springframework.context.annotation.Configuration
@Import(ResultInterceptor.class)
public class MybatisGenerator implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
    private static GeneratorInterceptor defaultInterceptor;
    private static ApplicationContext applicationContext;
    @Autowired(required = false) List<MapperFactoryBean> factoryBeans = new ArrayList<>();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        factoryBeans.forEach(bean -> {
            Class<?> ec = Reflection.getEntityClass(bean.getMapperInterface());
            if (ec != null) {
                Configuration conf = bean.getSqlSession().getConfiguration();
                MapperStatementParser parser = new MapperStatementParser(conf, bean.getMapperInterface());
                parser.parse();

                EntityMeta em = EntityMeta.get(ec);
                em.getSecondaryQueryFieldViewMap().keySet().forEach(f -> {
                    try {
                        EntityNestQueryGenerator.generate(conf, em.getEntityClass().getDeclaredField(f));
                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MybatisGenerator.applicationContext = applicationContext;
    }

    public static void setDefaultInterceptor(GeneratorInterceptor defaultInterceptor) {
        MybatisGenerator.defaultInterceptor = defaultInterceptor;
    }

    public static void intercept(InterceptorContext context) {
        AnnotationAttributes attr = AnnotatedElementUtils.getMergedAnnotationAttributes(context.getMethod(), GeneratedSql.class);
        if (!attr.getString("interceptor").isEmpty()) {
            try {
                Method method = context.getMapperClass().getMethod(attr.getString("interceptor"), InterceptorContext.class);
                if (Modifier.isStatic(method.getModifiers())) {
                    method.invoke(null, context);
                } else {
                    method.invoke(applicationContext.getBean(context.getMapperClass()), context);
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } else if (defaultInterceptor != null) {
            defaultInterceptor.intercept(context);
        }
    }
}
